<?php
	if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['checkuser']) || $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['checkchar']) || $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['checkemail']) || $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['register']))
	{
		session_start();
		include('_func_database.php');
		include('_func_main.php');
		
		if(isset($_GET['checkuser']))
		{
			$q = mysql_query("SELECT * FROM account WHERE username='".$_POST['udata']."'");
			echo mysql_num_rows($q);
		}

		if(isset($_GET['checkchar']))
		{
			$q = mysql_query("SELECT * FROM characters WHERE name='".$_POST['cdata']."'");
			echo mysql_num_rows($q);
		}

		if(isset($_GET['checkemail']))
		{
			$q = mysql_query("SELECT * FROM account WHERE email='".$_POST['edata']."'");
			echo mysql_num_rows($q);
		}

		if(isset($_GET['register']))
		{
			$uname = $_POST['username'];
			$password = $_POST['password'];
			$email = $_POST['email'];
			$fname = $_POST['fname'];
			$lname = $_POST['lname'];
			$cname = $_POST['cname'];
			$cpic = $_POST['cpic'];

			$password = encrypt($password);

			$activationkey = randomKey();

			if(mysql_query("INSERT INTO account 
						(username, password, email, bio, firstname, lastname, activationkey) 
						VALUES
						('$uname', '$password', '$email','This user has nothing to share.', '$fname', '$lname', '$activationkey')")or die(mysql_error()))
			{
				if(mysql_query("INSERT INTO characters (aid, name, characterpic)
						VALUES
						((SELECT id  FROM account WHERE username = '$uname' LIMIT 1), '$cname', '$cpic')")or die(mysql_error()))
				{
					$headers  = 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

					$headers .= 'To: '.$email.'' . "\r\n";
					$headers .= 'From: MyLittleGangsters <mlg@jurienhamaker.net>' . "\r\n";
					
					$subject = '[MLG]Welcome to MyLittleGangsters, '.$cname.'!';

					$body = '<b>Welcome to MyLittleGangsters</b><br>';
					$body .= 'Click the following link to activate your account:<br>';
					$body .= '<a href="http://mlg.jurienhamaker.net/?page=activate&email='.$email.'&key='.$activationkey.'">Click me!</a>';

					mail($receiver, $subject, $body, $headers);
					echo '<font color="green">Activation link has been send to your email.<br> Please check your spam folder.<br> Click <a href="index.php">Here</a> to go back.';
				}
			}

		}
	}
	
?>